package com.cabd.service.impl;

import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.Iterator;

import javax.servlet.http.Part;

import com.cabd.domain.Folder;
import com.cabd.service.FolderService;
import com.cabd.service.UploadService;
import com.cabd.staticfinal.StandardFileName;
import com.cabd.utils.CSVUtils;
import com.cabd.utils.UploadUtils;
import com.cabd.utils.XlsxUtils;

public class UpLoadServiceImpl implements UploadService {

	@Override
	public Boolean isUpLoad(String path, String folderName, Collection<Part> parts) throws IOException {
		
	    //获得迭代器并且把集合的第一个元素滤掉
	    Iterator<Part> iterator = parts.iterator();
	    iterator.next();
	    //检测目录是否存在，存在告诉客户端更换名称，不存在继续上传
	    Boolean b = UploadUtils.checkReFolder(folderName, path);
	    if(b) {
	 	    return false;
	    }
	    Folder folder = new Folder();
	    folder.setFolderName(folderName);
	    //获得新创建的目录完整路径
	    String savePath = path+"\\"+folderName;
	    File file = new File(savePath);
	    file.mkdir();
	    new File(savePath +"\\output").mkdir();
	    //创建标识，封装folder
	    int i = 1;
	    //将文件上传至服务器
	    while(iterator.hasNext()){
	    	Part part = iterator.next();
    		String header = part.getHeader("content-disposition");
    		String fileName = UploadUtils.getFileName(header);
    		System.out.println(fileName);
    		switch (i) {
			case 1:
				fileName = new String(StandardFileName.file1);
				folder.setFileName1(fileName);
				break;
			case 2:
				fileName = new String(StandardFileName.file2);
				folder.setFileName2(fileName);
				break;
			case 3:
				fileName = new String(StandardFileName.file3);
				folder.setFileName3(fileName);
				break;
			case 4:
				fileName = new String(StandardFileName.file4);
				folder.setFileName4(fileName);
				break;
			}
    		i++;
    		//屏蔽各平台之间分隔符的不同
    		part.write(savePath+File.separator+fileName);
    	}
	    System.out.println("成功上传文件："+folder.getFolderName() + "---" + folder.getFileName1() +", " + folder.getFileName2()
	    					+", "+folder.getFileName3() +", " + folder.getFileName4() +", "+folder.getFileName4());
	    //生成结果文件
	    CSVUtils.changeHeaders(folderName);
	    XlsxUtils.changeHeaders(folderName);
	    HandleDataWithPythonImpl handleDataWithPython = new HandleDataWithPythonImpl();
	    try {
			handleDataWithPython.creatResultFile1(folderName);
			handleDataWithPython.creatResultFile2(folderName);
		} catch (InterruptedException e) {
			System.err.println("兄弟，别开玩笑啊！！");
			e.printStackTrace();
		}
	    System.out.println("成功生成结果文件！");
	    
	    folder.setResultFile(StandardFileName.resultFile);
	    FolderService folderService = new FolderServiceImpl();
	    folderService.addService(folder);
	    return true;
	}

}
